<!DOCTYPE html>
<html layout:decorator="fragments/layout" th:with="index='admin',son='list'" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:layout="http://www.thymeleaf.org/" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>管理员管理</title>
    <style>
        .tag [data-role="remove"]::after {
            content: "x";
            padding: 0px 2px;
        }

        .tag [data-role="remove"] {
            margin-left: 8px;
            cursor: pointer;
        }

        .tag {
            margin-right: 5px;
        }

    </style>
</head>
<body>
<div layout:fragment="modal">
    <div class="modal" id="createModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">添加管理员</h4>
                </div>
                <div class="modal-body">
                    <div class="form-horizontal">
                        <div class="box-body">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">帐号</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="c-username" placeholder="请输入帐号"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">密码</label>
                                <div class="col-sm-10">
                                    <input type="password" class="form-control" id="c-password" placeholder="请输入密码"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">确认密码</label>
                                <div class="col-sm-10">
                                    <input type="password" class="form-control" id="c-password1" placeholder="请再次输入密码"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="createModalAdd">添加</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="authModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">管理员授权</h4>
                </div>
                <div class="modal-body">
                    <div class="form-horizontal">
                        <div class="box-body">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">帐号</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="auth-username" disabled/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">权限组</label>
                                <div class="col-sm-9">
                                    <select type="password" class="form-control" id="auth-role">
                                        <option value="-1">请选择权限组</option>
                                        <option value="1">超级管理员</option>
                                        <option value="2">用户运营组</option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-primary col-sm-1" id="auth-add"
                                        onclick="addAuth()"><i
                                        class="fa fa-plus"></i></button>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">已选</label>
                                <div class="col-sm-8" id="auth-group">
                                    <span class="tag label label-default">Sydney<span
                                            data-role="remove"></span></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="authModalConfirm">授权确认</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="modifyModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span></button>
                    <h4 class="modal-title">修改密码</h4>
                </div>
                <div class="modal-body">
                    <div class="form-horizontal">
                        <div class="box-body">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">帐号</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="m-username" placeholder="请输入帐号"
                                           disabled/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">新密码</label>
                                <div class="col-sm-10">
                                    <input type="password" class="form-control" id="m-password" placeholder="请输入新密码"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">确认新密码</label>
                                <div class="col-sm-10">
                                    <input type="password" class="form-control" id="m-password1"
                                           placeholder="请再次输入新密码"/>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="modifyModalModify">修改密码</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div layout:fragment="content">

    <section class="content-header">
        <h1>
            管理员管理
            <small>管理员列表</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-user"></i> 管理员管理</a></li>
            <li class="active">管理员列表</li>
        </ol>
    </section>

    <section class="content">
        <div class="box">
            <div class="box-body" id="search-form">
                <div class="row">
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>帐号</label>
                            <input class="form-control" id="s-username">
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <label style="visibility: hidden">为了好看</label>
                        <div class="form-group">
                            <button type="button" id="clear" class="btn btn-default">清空</button>
                            <button type="button" id="search" class="btn btn-default">查询</button>
                            <button type="button" data-toggle="modal" data-target="#createModal"
                                    class="btn btn-primary">添加管理员
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="box">
            <div class="box-body">
                <table id="dms-table" class="table table-bordered table-hover">
                    <thead align="text-center">
                    <tr>
                        <th>id</th>
                        <th>帐号</th>
                        <th>密码</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>

            </div>
        </div>
    </section>

</div>

<div layout:fragment="js">
    <script th:inline="javascript">
        var oTable = $('#dms-table');
        var currentId;
        var authArray = [];

        $('#search').click(function (e) {
            e.preventDefault();
            oTable.DataTable().ajax.reload();
        });

        $('#clear').click(function () {
            reloadTable();
        });

        $('#modifyModalModify').on('click', modifyModal);

        $('#createModalAdd').on('click', createModal);

        function clearModal() {
            $('#c-username').val('');
            $('#c-password').val('');
            $('#c-password1').val('');
        }

        function createModal() {
            var username = $('#c-username').val();
            var password = $('#c-password').val();
            var password1 = $('#c-password1').val();

            var validArgs = {
                "请输入帐号": username,
                "请输入密码": password,
                "请输入确认密码": password1,
            };
            //验证是否为空
            if (!validateArgs(validArgs)) {
                return;
            }

            if (password != password1) {
                toastr.error('请确认两次密码是否一致');
                return;
            }

            $.ajax({
                url: '/admins',
                type: 'post',
                dataType: 'json',
                data: {
                    "username": username,
                    "password": password
                },
                success: function (data) {
                    if (data['code'] == 200) {
                        toastr.success('添加管理员成功');
                        $('#createModal').modal('hide');
                        clearModal();
                        redraw();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var jsonObj = JSON.parse(XMLHttpRequest.responseText);
                    if (XMLHttpRequest.status == 400) {
                        toastr.error(jsonObj['msg']);
                    }
                }
            })
        }

        function modifyModal() {
            var oldpassword = $('#m-oldpassword').val();
            var password = $('#m-password').val();
            var password1 = $('#m-password1').val();

            var validArgs = {
//                "请输入旧密码": oldpassword,
                "请输入新密码": password,
                "请输入确认新密码": password1,
            };
            //验证是否为空
            if (!validateArgs(validArgs)) {
                return;
            }

            if (password != password1) {
                toastr.error('确保两次密码一致');
                return;
            }

            $.ajax({
                url: '/admins/' + currentId,
                type: 'put',
                dataType: 'json',
                data: {
                    "oldpass": oldpassword,
                    "password": password
                },
                success: function (data) {
                    if (data['code'] == 200) {
                        toastr.success('修改密码成功');
                        $('#modifyModal').modal("hide");
                        redraw();
                    } else {
                        toastr.error('修改密码失败：' + data['msg']);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var jsonObj = JSON.parse(XMLHttpRequest.responseText);
                    if (XMLHttpRequest.status == 400) {
                        toastr.error(jsonObj['msg']);
                    }
                }
            })
        }

        $('#dms-table').find('tbody').on('click', 'tr button.modify', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();

            $('#m-oldpassword').val('');
            $('#m-username').val(data.username);
            $('#m-password').val('');
            $('#m-password1').val('');

            currentId = data['id'];

            $('#modifyModal').modal("show");
        });

        $('#dms-table tbody').on('click', 'tr button.auth', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();
            $('#auth-username').val(data.username);
            currentId = data['id'];
            loadAdminRoles(currentId);
            authArray = [];

            $('#authModal').modal("show");
        });

        $('#dms-table tbody').on('click', 'tr button.delete', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();

            swal({
                title: "删除该管理员【" + data.username + "】",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#5ECD1E",
                confirmButtonText: "Yes, 确定",
                cancelButtonText: "No, 取消",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: "/admins/" + data['id'],
                        type: "delete",
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 200) {
                                toastr.success("删除成功");
                            } else {
                                toastr.error(data.msg);
                            }
                            redraw();
                        }
                    });
                }
            });
        });

        function reloadTable() {
            resetForm('search-form');   //重置所有input select
            oTable.DataTable().ajax.reload();
        }

        function redraw() {
            oTable.DataTable().draw(false);
        }

        function generateBtns(data, type, full, meta) {
            var temp = '';
            if (full.username == 'root') {
                temp = '禁止操作root超级管理员';
            } else {
                temp =
                    '<div class="btn-group">' +
                    '<button class="modify btn btn-xs btn-info">修改密码</button>' +
                    '<button class="auth btn btn-xs btn-warning">授权</button>' +
                    '<button class="delete btn btn-xs btn-danger">删除</button>' +
                    '</div>';
            }

            return temp;
        }

        //加载管理员的权限组
        function loadAdminRoles(adminId) {
            $.ajax({
                url: "/admins/adminRoles",
                type: "get",
                data: "adminId=" + adminId,
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        var authRole = $('#auth-role');
                        authRole.html('');
                        authRole.append('<option value="-1">请选择权限组</option>');
                        $.each(data, function (index, val) {
                            authRole.append('<option value="' + val.id + '">' + val.description + '</option>');
                        })

                        var authGroup = $('#auth-group');
                        authGroup.html("");
                        $.each(data, function (index, val) {
                            if (val.checked) {
                                authArray.push(val.id + '');
                                authGroup.append('<span class="tag label label-default" data-ref="' + val.id + '">' + val.description + '<span ' +
                                    'data-role="remove"></span></span>');
                            }
                        })
                    }
                }
            });
        }

        //更新管理员的权限组
        function updateAdminRoles(adminId, roleIds) {
            $.ajax({
                url: "/admins/adminRoles",
                type: "post",
                data: "adminId=" + adminId + "&roleIds=" + roleIds,
                dataType: "json",
                success: function (data) {
                    if (data.code == 200) {
                        $('#authModal').modal("toggle");
                        toastr.success("管理员权限修改成功");
                    } else {
                        toastr.error(data.msg);
                    }
                }
            });
        }

        //添加权限组
        function addAuth() {
            var val = $('#auth-role').val();
            var option = $('#auth-role').find(":selected").text();
            if (val != -1) {
                var index = authArray.indexOf(val);
                if (index < 0) {
                    //如果找不到 则添加
                    authArray.push(val);
                    $('#auth-group').append('<span class="tag label label-default" data-ref="' + val + '">' + option + '<span ' +
                        'data-role="remove"></span></span>');
                }
            }
        }

        //移除权限组 $e 为 tag
        function remove($e) {
            var tagId = $e.attr('data-ref').trim();
//            for (var i in authArray) console.log(typeof authArray[i] + "," + authArray[i])
            var index = authArray.indexOf(tagId);
//            console.log("tagId:" + tagId + "," + index + "authArray:" + authArray);
            if (index >= 0) {
                authArray.splice(index, 1);
            }
            $e.remove();
        }

        function planify(data) {
            for (var i = 0; i < data.columns.length; i++) {
                column = data.columns[i];
                delete(column.search);
                delete(column.searchable);
                delete(column.orderable);
                delete(column.name);
                delete(column.data);
            }
            data.username = $('#s-username').val();
            delete(data.search);
        }

        function dtinit() {
            var url = "/admins/page";
            oTable.DataTable({
                serverSide: true,
                ordering: false,
                searching: false,
                stateSave: false,
                autoWidth: false,
                pagingType: "full_numbers",
                lengthMenu: [
                    [10, 25, 50, 100],
                    [10, 25, 50, 100]
                ],
                ajax: {
                    url: url,
                    type: 'GET',
                    data: function (data) {
                        planify(data);
                    }
                },
                columns: [
                    {
                        data: 'id',
                    },
                    {
                        data: 'username',
                    },
                    {
                        data: 'password',
                        render: function () {
                            return '********';
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'id',
                        render: function (data, type, full, meta) {
                            return generateBtns(data, type, full, meta);
                        }
                    }

                ],
                columnDefs: [{
                    targets: "_all",
                    defaultContent: "空"
                }, {
                    targets: "_all",
                    className: 'text-center',
                    orderable: false
                }],
                language: {
                    "lengthMenu": "每页 _MENU_ 条记录",
                    "zeroRecords": "<h4 class='text-center'>没有找到记录</h4>",
                    "info": "显示 _START_ 到 _END_ 行，总共 _TOTAL_ 行， 第 _PAGE_ 页 ( 共 _PAGES_ 页 )",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤1)",
                    "search": "查询：",
                    "paginate": {
                        "first": "首页",
                        "last": "尾页",
                        "previous": "上一页",
                        "next": "下一页"
                    }
                }
            });
        }

        $(document).ready(function () {
            dtinit();

            $('#auth-group').on('click', '.tag span[data-role="remove"]', function (e) {
                e.preventDefault();
                remove($(this).closest('.tag'));
            })

            $('#authModalConfirm').on('click', function (e) {
                e.preventDefault();
                var adminId = currentId;
                var roleIds = authArray.join(',');
                updateAdminRoles(adminId, roleIds);
            })
        })
    </script>
</div>
</body>
</html>
